package com.jumi.microservice.service.order;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelCommonException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.utils.EnumUtil;
import com.jumi.microservice.constant.PayChannelEnum;
import com.jumi.microservice.constant.compensation.AfterSaleStatusEnum;
import com.jumi.microservice.dto.admin.ExportExcelRequest;
import com.jumi.microservice.dto.admin.ExportExcelResponse;
import com.jumi.microservice.dto.excel.*;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.entity.LogisticsGoods;
import com.jumi.microservice.entity.OrderGoods;
import com.jumi.microservice.entity.OrderLog;
import com.jumi.microservice.entity.UserOrder;
import com.jumi.microservice.enumerate.*;
import com.jumi.microservice.mapper.LogisticsGoodsMapper;
import com.jumi.microservice.mapper.OrderGoodsMapper;
import com.jumi.microservice.mapper.OrderLogMapper;
import com.jumi.microservice.mapper.UserOrderMapper;
import com.jumi.microservice.material.dto.supplier.JmSupplierResponse;
import com.jumi.microservice.material.dto.warehouse.JmWarehouseResponse;
import com.jumi.microservice.material.service.IJmSupplierService;
import com.jumi.microservice.material.service.IJmWarehouseService;
import com.jumi.microservice.service.CommodityApi;
import com.jumi.microservice.service.IMemberService;
import com.jumi.microservice.service.IOrderDubboService;
import com.jumi.microservice.service.excelListener.ExcelListener;
import com.jumi.microservice.service.logistics.admin.AsyncSendService;
import com.jumi.microservice.service.logistics.admin.SendService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangjingdao
 */
@Service
public class ExportExcelServiceImpl {

    @Resource
    UserOrderMapper userOrderMapper;
    @Resource
    OrderGoodsMapper orderGoodsMapper;
    @DubboReference
    IJmSupplierService iJmSupplierService;
    @DubboReference
    IJmWarehouseService iJmWarehouseService;
    @DubboReference
    IMemberService iMemberService;
    @Resource
    SendService sendService;
    @Resource
    LogisticsGoodsMapper logisticsGoodsMapper;
    @DubboReference
    IOrderDubboService iOrderDubboService;
    @DubboReference
    CommodityApi commodityApi;
    @Resource
    OrderLogMapper orderLogMapper;
    @Resource
    AsyncSendService asyncSendService;

    public ExportExcelCommonResponse<ExportExcelResponse> exportExcel(ExportExcelRequest request) {
        ExportExcelCommonResponse<ExportExcelResponse> exportExcelResponseExportExcelCommonResponse = new ExportExcelCommonResponse<>();
        QueryWrapper<UserOrder> queryWrapper = new QueryWrapper<>();
        if (request.getOrderNo() != null) {
            queryWrapper.eq("order_no", request.getOrderNo());
        }
        if (request.getOrderStatus() != null) {
            queryWrapper.eq("order_status", request.getOrderStatus());
        }
        if (request.getPayTime() != null) {
            queryWrapper.eq("pay_time", request.getPayTime());
        }
        if (request.getPhone() != null) {
            //手机号
        }
        if (request.getOrderId() != null) {
            queryWrapper.eq("id", request.getOrderId());
        }
        List<UserOrder> userOrders = userOrderMapper.selectList(queryWrapper);
        List<ExportExcelResponse> exportExcelResponses = new ArrayList<>();
        userOrders.forEach(
                userOrder -> {
                    ExportExcelResponse exportExcelResponse = new ExportExcelResponse();
                    BeanUtils.copyProperties(userOrder, exportExcelResponse);
                    exportExcelResponses.add(exportExcelResponse);
                }
        );
        String fileName = "全部订单" + System.currentTimeMillis() + ".xlsx";
        exportExcelResponseExportExcelCommonResponse.setData(exportExcelResponses);
        exportExcelResponseExportExcelCommonResponse.setFileName(fileName);
        return exportExcelResponseExportExcelCommonResponse;
    }

    public ExportExcelCommonResponse<ExportOrderAllResponseC> exportOrderAllResponse(ExportOrderGoodsRequest request) {
        ExportExcelCommonResponse<ExportOrderAllResponseC> exportExcelCommonResponse = new ExportExcelCommonResponse<>();
        List<ExportOrderAllResponseC> exportOrderAllResponses = new ArrayList<>();
        Long uid = null;
        if (request.getPhoneType() != null && request.getPhoneType() == 1) {
            Integer u = iMemberService.getUidByMobile(request.getPhone()).getData();
            if (u != null) {
                uid = u.longValue();
            } else {
                return exportExcelCommonResponse;
            }
        }
        List<UserOrderGoodsInfo> orderGoodsInfos = userOrderMapper.getAllOrders(request.getId(), request.getStartTime(), request.getEndTime(), request.getGoodsName(), request.getType(), request.getSupplier(), request.getPhoneType(), uid, request.getPhone(), request.getOrderNo(), request.getPayNo(), request.getStartPayTime(), request.getEndPayTime());
        if (orderGoodsInfos.isEmpty()) {
            return exportExcelCommonResponse;
        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        Map<Integer, JmSupplierResponse> supplierMap = jmSupplierResponses.stream().collect(Collectors.toMap(s -> s.getSupplierId().intValue(), s -> s));
        //获取全部发货仓
        List<JmWarehouseResponse> iJmWarehouseServiceAll = iJmWarehouseService.findAll().getData();
        Map<Integer, JmWarehouseResponse> warehouseMap = iJmWarehouseServiceAll.stream().collect(Collectors.toMap(w -> w.getWarehouseId().intValue(), w -> w));
        for (UserOrderGoodsInfo good : orderGoodsInfos) {
            ExportOrderAllResponseC exportOrderAllResponse = new ExportOrderAllResponseC();
            exportOrderAllResponse.setPayTime(good.getPayTime() != null ? good.getPayTime() : null);
            exportOrderAllResponse.setNickName(good.getReceiverName());
            exportOrderAllResponse.setPhone(good.getReceiverPhone());
            exportOrderAllResponse.setAddress(good.getReceiverAddress());
            OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(good.getOrderStatus(), OrderStatusEnum.class);
            if (orderStatusEnum != null) {
                exportOrderAllResponse.setOrderStatus(orderStatusEnum.getMessage());
            }
            BeanUtils.copyProperties(good, exportOrderAllResponse);
            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(good.getGoodsStatus(), LogisticsStatusEnum.class);
            if (logisticsStatusEnum != null) {
                exportOrderAllResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
            }
            if (good.getSelfFlag().equals(SelfFlagEnum.YES_SELF.getCode())) {
                if (warehouseMap.containsKey(good.getRealWarehouse())) {
                    exportOrderAllResponse.setSupplierName(warehouseMap.get(good.getRealWarehouse()).getWarehouseName());
                }
            } else {
                if (supplierMap.containsKey(good.getSupplierId())) {
                    exportOrderAllResponse.setSupplierName(supplierMap.get(good.getSupplierId()).getSupplierCompanyName());
                }
            }
            AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(good.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
            if (afterSaleStatusEnum != null) {
                exportOrderAllResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
            }
            exportOrderAllResponses.add(exportOrderAllResponse);
        }
        exportExcelCommonResponse.setData(exportOrderAllResponses);
        exportExcelCommonResponse.setFileName("全部订单" + System.currentTimeMillis() + ".xlsx");
        return exportExcelCommonResponse;
    }

    public ExportExcelCommonResponse<ExportOrderAllResponseC> exportPreSaleResponse(ExportPreSaleRequest request) {
        ExportExcelCommonResponse<ExportOrderAllResponseC> exportExcelCommonResponse = new ExportExcelCommonResponse<>();
        List<ExportOrderAllResponseC> exportOrderAllResponses = new ArrayList<>();
        List<UserOrderGoodsInfo> orderGoodsInfos = userOrderMapper.getExportPreSaleOrders(request.getId(), request.getStartTime(), request.getEndTime(), request.getPayTime(), request.getPayEndTime(), request.getGoodsName());
        if (orderGoodsInfos.isEmpty()) {
            return exportExcelCommonResponse;
        }
        for (UserOrderGoodsInfo good : orderGoodsInfos) {
            ExportOrderAllResponseC exportOrderAllResponse = new ExportOrderAllResponseC();
            exportOrderAllResponse.setPayTime(good.getPayTime() != null ? good.getPayTime() : null);
            exportOrderAllResponse.setNickName(good.getReceiverName());
            exportOrderAllResponse.setPhone(good.getReceiverPhone());
            exportOrderAllResponse.setAddress(good.getReceiverAddress());
            OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(good.getOrderStatus(), OrderStatusEnum.class);
            if (orderStatusEnum != null) {
                exportOrderAllResponse.setOrderStatus(orderStatusEnum.getMessage());
            }
            BeanUtils.copyProperties(good, exportOrderAllResponse);
            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(good.getGoodsStatus(), LogisticsStatusEnum.class);
            if (logisticsStatusEnum != null) {
                exportOrderAllResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
            }
            exportOrderAllResponse.setSupplierName("未分配");
            AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(good.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
            if (afterSaleStatusEnum != null) {
                exportOrderAllResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
            }
            exportOrderAllResponses.add(exportOrderAllResponse);
        }
        exportExcelCommonResponse.setData(exportOrderAllResponses);
        exportExcelCommonResponse.setFileName("预售" + System.currentTimeMillis() + ".xlsx");
        return exportExcelCommonResponse;
    }

//    public ExportExcelCommonResponse<ExportOrderAllResponse> getNonSelfOperated(ExportNonSelfOperatedRequest
//                                                                                        request,Long uid,String name) {
//        ExportExcelCommonResponse<ExportOrderAllResponse> exportExcelCommonResponse = new ExportExcelCommonResponse<>();
//        List<ExportOrderAllResponse> exportOrderAllResponses = new ArrayList<>();
//        List<UserOrder> userOrders = userOrderMapper.getNonSelfOperatedOrders(request.getId(), request.getStartTime(), request.getEndTime(), request.getStartPayTime(), request.getEndPayTime(), request.getGoodsName(), request.getType(), request.getSupplierId());
//        if (userOrders.size() == 0) {
//            return exportExcelCommonResponse;
//        }
//        List<Integer> orderIds = userOrders.stream().map(UserOrder::getId).collect(Collectors.toList());
//        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
//        orderGoodsQueryWrapper.in("order_id", orderIds);
//        orderGoodsQueryWrapper.eq("self_flag", SelfFlagEnum.NO_SELF.getCode());
//        orderGoodsQueryWrapper.orderByDesc("create_time");
//        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
//        List<OrderGoods> goods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
//        if (goods.size() == 0) {
//            return exportExcelCommonResponse;
//        }
//        //获取全部供应商
//        List<JmSupplierResponse> jmSupplierResponses = getSupply();
//        Map<Integer, JmSupplierResponse> supplierMap = jmSupplierResponses.stream().collect(Collectors.toMap(s -> s.getSupplierId().intValue(), s -> s));
//        Map<Integer, UserOrder> userOrderMap = userOrders.stream().collect(Collectors.toMap(UserOrder::getId, s -> s));
//        Map<Integer,String> goodsCodeMap = commodityApi.getGoodsSkuThirdPartyCode(goods.stream().map(OrderGoods::getGoodsId).collect(Collectors.toList()));
//        List<Integer> orderIdList = new ArrayList<>();
//        List<JSONObject> addLogList = new ArrayList<>();
//        for (OrderGoods good : goods) {
//            Set<Byte> set = goods.stream().filter(g -> g.getOrderId().equals(good.getOrderId())).map(OrderGoods::getGoodsStatus).collect(Collectors.toSet());
//            if (set.contains(LogisticsStatusEnum.PART_SEND.getCode()) || set.contains(LogisticsStatusEnum.WAIT_RECEIVE.getCode())||good.getGoodsStatus().equals(LogisticsStatusEnum.CANCEL.getCode())) {
//                continue;
//            }
//            ExportOrderAllResponse exportOrderAllResponse = new ExportOrderAllResponse();
//            if (userOrderMap.containsKey(good.getOrderId())) {
//                UserOrder userOrder = userOrderMap.get(good.getOrderId());
//                exportOrderAllResponse.setOrderRemark(userOrder.getRemark());
//                exportOrderAllResponse.setBuyerId(userOrder.getBuyerId());
//                exportOrderAllResponse.setCreateTime(userOrder.getCreateTime());
//                if (userOrder.getPayTime() != null) {
//                    exportOrderAllResponse.setPayTime(userOrder.getPayTime());
//                }
//                exportOrderAllResponse.setNickName(userOrder.getReceiverName());
//                exportOrderAllResponse.setPhone(userOrder.getReceiverPhone());
//                exportOrderAllResponse.setAddress(userOrder.getReceiverAddress());
//                OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
//                if (orderStatusEnum != null) {
//                    exportOrderAllResponse.setOrderStatus(orderStatusEnum.getMessage());
//                }
//            }
//            BeanUtils.copyProperties(good, exportOrderAllResponse);
//            if(goodsCodeMap.containsKey(good.getGoodsId())){
//                exportOrderAllResponse.setGoodsCode(goodsCodeMap.get(good.getGoodsId()));
//            }
//            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(good.getGoodsStatus(), LogisticsStatusEnum.class);
//            if (logisticsStatusEnum != null) {
//                exportOrderAllResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
//            }
//            if (supplierMap.containsKey(good.getSupplierId())) {
//                exportOrderAllResponse.setSupplierName(supplierMap.get(good.getSupplierId()).getSupplierCompanyName());
//            }
//            AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(good.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
//            if (afterSaleStatusEnum != null) {
//                exportOrderAllResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
//            }
//            exportOrderAllResponse.setRealSendAmount(exportOrderAllResponse.getGoodsAmount());
//            exportOrderAllResponses.add(exportOrderAllResponse);
//            orderIdList.add(good.getOrderId());
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("uid",uid);
//            jsonObject.put("name",name);
//            jsonObject.put("orderNo",good.getOrderNo());
//            if(request.getIsUpdateOrderStatus().equals((byte) 1)){
//                jsonObject.put("log","自营未对接导出excel 订单号："+good.getOrderNo()+"，商品名称："+good.getGoodsName()+"，数量："+good.getGoodsAmount());
//            }else{
//                jsonObject.put("log","自营导出excel 订单号："+good.getOrderNo()+"，商品名称："+good.getGoodsName()+"，数量："+good.getGoodsAmount());
//            }
//            addLogList.add(jsonObject);
//        }
//        asyncSendService.batchAddLog(addLogList,new ArrayList<>());
//        if(request.getIsUpdateOrderStatus().equals((byte) 1)){
//            asyncSendService.batchUpdateOrderStatus(orderIdList);
//        }
//        exportExcelCommonResponse.setData(exportOrderAllResponses);
//        exportExcelCommonResponse.setFileName("非自营代发货" + System.currentTimeMillis() + ".xlsx");
//        return exportExcelCommonResponse;
//    }

    public ExportExcelCommonResponse<ExportOrderAllResponse> getNonSelfOperated(ExportNonSelfOperatedRequest
                                                                                        request,Long uid,String name) {
        ExportExcelCommonResponse<ExportOrderAllResponse> exportExcelCommonResponse = new ExportExcelCommonResponse<>();
        List<ExportOrderAllResponse> exportOrderAllResponses = new ArrayList<>();
        List<UserOrderGoodsInfo> userOrderGoodsInfos = userOrderMapper.getNonSelfOperatedOrders(request.getId(), request.getStartTime(), request.getEndTime(), request.getStartPayTime(), request.getEndPayTime(), request.getGoodsName(), request.getType(), request.getSupplierId());
        if (userOrderGoodsInfos.size() == 0) {
            return exportExcelCommonResponse;
        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        Map<Integer, JmSupplierResponse> supplierMap = jmSupplierResponses.stream().collect(Collectors.toMap(s -> s.getSupplierId().intValue(), s -> s));
        Map<Integer,String> goodsCodeMap = commodityApi.getGoodsSkuThirdPartyCode(userOrderGoodsInfos.stream().map(UserOrderGoodsInfo::getGoodsId).collect(Collectors.toList()));
        List<Integer> orderIdList = new ArrayList<>();
        List<JSONObject> addLogList = new ArrayList<>();
        for (UserOrderGoodsInfo good : userOrderGoodsInfos) {
            ExportOrderAllResponse exportOrderAllResponse = new ExportOrderAllResponse();
                exportOrderAllResponse.setOrderRemark(good.getOrderRemark());
                exportOrderAllResponse.setBuyerId(good.getBuyerId());
                exportOrderAllResponse.setCreateTime(good.getOrderCreateTime());
                exportOrderAllResponse.setPayTime(good.getPayTime());
                exportOrderAllResponse.setNickName(good.getReceiverName());
                exportOrderAllResponse.setPhone(good.getReceiverPhone());
                exportOrderAllResponse.setAddress(good.getReceiverAddress());
                OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(good.getOrderStatus(), OrderStatusEnum.class);
                if (orderStatusEnum != null) {
                    exportOrderAllResponse.setOrderStatus(orderStatusEnum.getMessage());
                }
            BeanUtils.copyProperties(good, exportOrderAllResponse);
            if(goodsCodeMap.containsKey(good.getGoodsId())){
                exportOrderAllResponse.setGoodsCode(goodsCodeMap.get(good.getGoodsId()));
            }
            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(good.getGoodsStatus(), LogisticsStatusEnum.class);
            if (logisticsStatusEnum != null) {
                exportOrderAllResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
            }
            if (supplierMap.containsKey(good.getSupplierId())) {
                exportOrderAllResponse.setSupplierName(supplierMap.get(good.getSupplierId()).getSupplierCompanyName());
            }
            AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(good.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
            if (afterSaleStatusEnum != null) {
                exportOrderAllResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
            }
            exportOrderAllResponse.setRealSendAmount(exportOrderAllResponse.getGoodsAmount());
            exportOrderAllResponses.add(exportOrderAllResponse);
            orderIdList.add(good.getOrderId());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("uid",uid);
            jsonObject.put("name",name);
            jsonObject.put("orderNo",good.getOrderNo());
            if(request.getIsUpdateOrderStatus().equals((byte) 1)){
                jsonObject.put("log","非自营未对接导出excel 订单号："+good.getOrderNo()+"，商品名称："+good.getGoodsName()+"，数量："+good.getGoodsAmount());
            }else{
                jsonObject.put("log","非自营导出excel 订单号："+good.getOrderNo()+"，商品名称："+good.getGoodsName()+"，数量："+good.getGoodsAmount());
            }
            addLogList.add(jsonObject);
        }
        asyncSendService.batchAddLog(addLogList,new ArrayList<>());
        if(request.getIsUpdateOrderStatus().equals((byte) 1)){
            asyncSendService.batchUpdateOrderStatus(orderIdList);
        }
        exportExcelCommonResponse.setData(exportOrderAllResponses);
        exportExcelCommonResponse.setFileName("非自营代发货" + System.currentTimeMillis() + ".xlsx");
        return exportExcelCommonResponse;
    }

    /**
     * 插入日志记录表
     *
     * @param uid
     * @param name
     * @param orderNo
     * @param log
     */
    @Async
    public boolean addLog(Long uid, String name, String orderNo, String log) {
        OrderLog orderLog = new OrderLog();
        orderLog.setOperatorId(uid);
        orderLog.setOperatorName(name);
        orderLog.setOrderSn(orderNo);
        orderLog.setLog(log);
        orderLog.setUserFlag((byte) 2);
        int rows = orderLogMapper.insert(orderLog);
        return rows > 0;
    }

    public ExportExcelCommonResponse<ExportOrderAllResponse> getPartial(ExportPartialRequest request,Long uid,String name) {
        ExportExcelCommonResponse<ExportOrderAllResponse> exportExcelCommonResponse = new ExportExcelCommonResponse<>();
        List<ExportOrderAllResponse> exportOrderAllResponses = new ArrayList<>();
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        if (request.getId() != null) {
            orderGoodsQueryWrapper.in("order_id", request.getId().split(","));
        }
        if (request.getType() != null && request.getType().equals(SupplierTypeEnum.SUPPLIER.getCode())) {
            orderGoodsQueryWrapper.eq("supplier_id", request.getSupplierId());
        } else if (request.getType() != null && request.getType().equals(SupplierTypeEnum.DELIVERY_WAREHOUSE.getCode())) {
            orderGoodsQueryWrapper.eq("real_warehouse", request.getSupplierId());
        }
        if (request.getGoodsName() != null) {
            orderGoodsQueryWrapper.like("goods_name", request.getGoodsName());
        }

        orderGoodsQueryWrapper.eq("del_flag", DelFlag.NORMAL);
//            orderGoodsQueryWrapper.in("goods_status", LogisticsStatusEnum.PART_SEND.getCode(), LogisticsStatusEnum.WAIT_SEND.getCode());
        orderGoodsQueryWrapper.ge("goods_status", LogisticsStatusEnum.WAIT_SEND.getCode());
        if (request.getStartTime() != null && request.getEndTime() != null) {
            orderGoodsQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (request.getOrderNo() != null) {
            orderGoodsQueryWrapper.eq("order_no", request.getOrderNo());
        }
        List<OrderGoods> goods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
        if (goods.isEmpty()) {
            exportExcelCommonResponse.setFileName("部分发货" + System.currentTimeMillis());
            return exportExcelCommonResponse;
        }
        List<Integer> orderId = goods.stream().map(OrderGoods::getOrderId).collect(Collectors.toList());
//        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        //获取全部发货仓
        ResponseResult<List<JmWarehouseResponse>> iJmWarehouseServiceAll = iJmWarehouseService.findAll();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        List<Integer> goodsIds =  goods.stream()
                .filter(g->g.getSelfFlag().equals(SelfFlagEnum.NO_SELF.getCode())).map(OrderGoods::getGoodsId)
                .collect(Collectors.toList());
        Map<Integer,String> goodsCodeMap = commodityApi.getGoodsSkuThirdPartyCode(goodsIds.isEmpty()?null:goodsIds);
//        userOrderQueryWrapper.eq("del_flag", DelFlag.NORMAL);
        userOrderQueryWrapper.in("id", orderId);
        List<UserOrder> userOrderList = userOrderMapper.selectList(userOrderQueryWrapper);
        Map<Integer, UserOrder> orderMap = new HashMap<>(userOrderList.size());
        List<JSONObject> addLogList = new ArrayList<>();
        for (UserOrder userOrder : userOrderList) {
            orderMap.put(userOrder.getId(), userOrder);
        }
        for (OrderGoods good : goods) {
            if (good.getGoodsStatus().equals(LogisticsStatusEnum.WAIT_RECEIVE.getCode()) ||
                    good.getGoodsStatus().equals(LogisticsStatusEnum.CONFIRM_RECEIVE.getCode())) {
                continue;
            }
            List<OrderGoods> ll = goods.stream().filter(g -> g.getOrderId().equals(good.getOrderId())).collect(Collectors.toList());
            Set<Byte> set = ll.stream().map(OrderGoods::getGoodsStatus).collect(Collectors.toSet());
            if (set.size() == 1 && set.contains(LogisticsStatusEnum.WAIT_SEND.getCode())) {
                continue;
            }
            ExportOrderAllResponse exportOrderAllResponse = new ExportOrderAllResponse();
            if (orderMap.containsKey(good.getOrderId())) {
                UserOrder userOrder = orderMap.get(good.getOrderId());
                exportOrderAllResponse.setOrderId(userOrder.getId());
                exportOrderAllResponse.setOrderNo(userOrder.getOrderNo());
                exportOrderAllResponse.setBuyerId(userOrder.getBuyerId());
                exportOrderAllResponse.setCreateTime(userOrder.getCreateTime());
                if (userOrder.getPayTime() != null) {
                    exportOrderAllResponse.setPayTime(userOrder.getPayTime());
                    exportOrderAllResponse.setOrderRemark(userOrder.getRemark());
                }
                exportOrderAllResponse.setNickName(userOrder.getReceiverName());
                exportOrderAllResponse.setPhone(userOrder.getReceiverPhone());
                exportOrderAllResponse.setAddress(userOrder.getReceiverAddress());
                OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(userOrder.getOrderStatus(), OrderStatusEnum.class);
                if (orderStatusEnum != null) {
                    exportOrderAllResponse.setOrderStatus(orderStatusEnum.getMessage());
                }
            }
            BeanUtils.copyProperties(good, exportOrderAllResponse);
            if(goodsCodeMap!=null && goodsCodeMap.containsKey(good.getGoodsId())){
                exportOrderAllResponse.setGoodsCode(goodsCodeMap.get(good.getGoodsId()));
            }
            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(good.getGoodsStatus(), LogisticsStatusEnum.class);
            if (logisticsStatusEnum != null) {
                exportOrderAllResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
            }
            if (good.getSelfFlag().equals(SelfFlagEnum.YES_SELF.getCode())) {
                for (JmWarehouseResponse datum : iJmWarehouseServiceAll.getData()) {
                    if (good.getRealWarehouse().longValue() == datum.getWarehouseId()) {
                        exportOrderAllResponse.setSupplierName(datum.getWarehouseName());
                    }
                }
            } else if (good.getSelfFlag().equals(SelfFlagEnum.NO_SELF.getCode())) {
                for (JmSupplierResponse datum : jmSupplierResponses) {
                    if (good.getSupplierId().equals(datum.getSupplierId().intValue())) {
                        exportOrderAllResponse.setSupplierName(datum.getSupplierCompanyName());
                    }
                }
            }
            exportOrderAllResponse.setGoodsAmount(good.getGoodsAmount() - good.getRealSendAmount());
            exportOrderAllResponse.setRealSendAmount(good.getGoodsAmount() - good.getRealSendAmount());
            AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(good.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
            if (afterSaleStatusEnum != null) {
                exportOrderAllResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
            }
            exportOrderAllResponse.setOrderStatus("待收货");
            exportOrderAllResponse.setRemark("");
            exportOrderAllResponses.add(exportOrderAllResponse);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("uid",uid);
            jsonObject.put("name",name);
            jsonObject.put("orderNo",good.getOrderNo());
            jsonObject.put("log","部分发货导出excel 订单号："+good.getOrderNo()+"，商品名称："+good.getGoodsName()+"，数量："+(good.getGoodsAmount()-good.getRealSendAmount()));
            addLogList.add(jsonObject);
        }
        asyncSendService.batchAddLog(addLogList,new ArrayList<>());
        exportExcelCommonResponse.setData(exportOrderAllResponses);
        exportExcelCommonResponse.setFileName("部分发货" + System.currentTimeMillis() + ".xlsx");
        return exportExcelCommonResponse;
    }

    public ExportExcelCommonResponse<ExportOrderAllResponseC> getGoodsReceived(ExportGoodsReceivedRequest request) {
        ExportExcelCommonResponse<ExportOrderAllResponseC> exportExcelCommonResponse = new ExportExcelCommonResponse<>();
        List<ExportOrderAllResponseC> exportOrderAllResponses = new ArrayList<>();
        String flag = null;
        if (request.getLogisticsNo() != null && !request.getLogisticsNo().isEmpty()) {
            QueryWrapper<LogisticsGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("del_flag", 0).eq("real_logistics_no", request.getLogisticsNo());
            List<LogisticsGoods> list = logisticsGoodsMapper.selectList(queryWrapper);
            List<Integer> orderIds = list.stream().map(LogisticsGoods::getOrderId).collect(Collectors.toList());
            if (orderIds.isEmpty()) {
                exportExcelCommonResponse.setData(exportOrderAllResponses);
                return exportExcelCommonResponse;
            }
            flag = list.stream().map(l -> l.getOrderId().toString()).collect(Collectors.joining(","));
        }
        Long uid = null;
        if (request.getPhoneType() != null && request.getPhoneType().equals(PhoneTypeEnum.BUYER.getCode())) {
            //根据手机号获取uid 加进去
            Integer u = iMemberService.getUidByMobile(request.getPhone()).getData();
            if (u != null) {
                uid = u.longValue();
            } else {
                return exportExcelCommonResponse;
            }
        }
        List<UserOrderGoodsInfo> orderGoodsInfos = userOrderMapper.getGoodsReceivedOrders(request.getId(), flag, request.getStartTime(), request.getEndTime(), request.getGoodsName(), request.getType(), request.getSupplierId(), request.getPhoneType(), uid, request.getPhone());
        if (orderGoodsInfos.isEmpty()) {
            return exportExcelCommonResponse;
        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        Map<Integer, JmSupplierResponse> supplyMap = jmSupplierResponses.stream().collect(Collectors.toMap(s -> s.getSupplierId().intValue(), s -> s));
        //获取全部发货仓
        List<JmWarehouseResponse> iJmWarehouseServiceAll = iJmWarehouseService.findAll().getData();
        Map<Integer, JmWarehouseResponse> warehouseMap = iJmWarehouseServiceAll.stream().collect(Collectors.toMap(s -> s.getWarehouseId().intValue(), s -> s));
        for (UserOrderGoodsInfo good : orderGoodsInfos) {
            ExportOrderAllResponseC exportOrderAllResponse = new ExportOrderAllResponseC();
            exportOrderAllResponse.setPayTime(good.getPayTime() != null ? good.getPayTime() : null);
            exportOrderAllResponse.setNickName(good.getReceiverName());
            exportOrderAllResponse.setPhone(good.getReceiverPhone());
            exportOrderAllResponse.setAddress(good.getReceiverAddress());
            OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(good.getOrderStatus(), OrderStatusEnum.class);
            if (orderStatusEnum != null) {
                exportOrderAllResponse.setOrderStatus(orderStatusEnum.getMessage());
            }
            BeanUtils.copyProperties(good, exportOrderAllResponse);
            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(good.getGoodsStatus(), LogisticsStatusEnum.class);
            if (logisticsStatusEnum != null) {
                exportOrderAllResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
            }
            if (good.getSelfFlag().equals(SelfFlagEnum.YES_SELF.getCode())) {
                if (warehouseMap.containsKey(good.getRealWarehouse())) {
                    exportOrderAllResponse.setSupplierName(warehouseMap.get(good.getRealWarehouse()).getWarehouseName());
                }
            } else {
                if (supplyMap.containsKey(good.getSupplierId())) {
                    exportOrderAllResponse.setSupplierName(supplyMap.get(good.getSupplierId()).getSupplierCompanyName());
                }
            }
            AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(good.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
            if (afterSaleStatusEnum != null) {
                exportOrderAllResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
            }
            exportOrderAllResponses.add(exportOrderAllResponse);
        }
        exportExcelCommonResponse.setData(exportOrderAllResponses);
        exportExcelCommonResponse.setFileName("待收货" + System.currentTimeMillis() + ".xlsx");
        return exportExcelCommonResponse;
    }

    public ExportExcelCommonResponse<ExportOrderAllResponseC> getCompletedList(ExportCompletedRequest request) {
        ExportExcelCommonResponse<ExportOrderAllResponseC> exportExcelCommonResponse = new ExportExcelCommonResponse<>();
        List<ExportOrderAllResponseC> exportOrderAllResponses = new ArrayList<>();
        String flag = null;
        if (request.getLogisticsNo() != null && !request.getLogisticsNo().isEmpty()) {
            QueryWrapper<LogisticsGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("del_flag", 0).eq("real_logistics_no", request.getLogisticsNo());
            List<LogisticsGoods> list = logisticsGoodsMapper.selectList(queryWrapper);
            List<Integer> orderIds = list.stream().map(LogisticsGoods::getOrderId).collect(Collectors.toList());
            if (orderIds.isEmpty()) {
                return exportExcelCommonResponse;
            }
            flag = list.stream().map(l -> l.getOrderId().toString()).collect(Collectors.joining(","));
        }
        List<UserOrderGoodsInfo> orderGoodsInfos = userOrderMapper.getCompletedListOrders(request.getId(), flag, request.getStartTime(), request.getEndTime(), request.getGoodsName(), request.getType(), request.getSupplierId());
        if (orderGoodsInfos.isEmpty()) {
            return exportExcelCommonResponse;
        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        Map<Integer, JmSupplierResponse> supplyMap = jmSupplierResponses.stream().collect(Collectors.toMap(s -> s.getSupplierId().intValue(), s -> s));
        //获取全部发货仓
        List<JmWarehouseResponse> iJmWarehouseServiceAll = iJmWarehouseService.findAll().getData();
        Map<Integer, JmWarehouseResponse> warehouseMap = iJmWarehouseServiceAll.stream().collect(Collectors.toMap(s -> s.getWarehouseId().intValue(), s -> s));
        for (UserOrderGoodsInfo good : orderGoodsInfos) {
            ExportOrderAllResponseC exportOrderAllResponse = new ExportOrderAllResponseC();
            exportOrderAllResponse.setPayTime(good.getPayTime() != null ? good.getPayTime() : null);
            exportOrderAllResponse.setNickName(good.getReceiverName());
            exportOrderAllResponse.setPhone(good.getReceiverPhone());
            exportOrderAllResponse.setAddress(good.getReceiverAddress());
            OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(good.getOrderStatus(), OrderStatusEnum.class);
            if (orderStatusEnum != null) {
                exportOrderAllResponse.setOrderStatus(orderStatusEnum.getMessage());
            }
            BeanUtils.copyProperties(good, exportOrderAllResponse);
            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(good.getGoodsStatus(), LogisticsStatusEnum.class);
            if (logisticsStatusEnum != null) {
                exportOrderAllResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
            }
            if (good.getSelfFlag().equals(SelfFlagEnum.YES_SELF.getCode())) {
                if (warehouseMap.containsKey(good.getRealWarehouse())) {
                    exportOrderAllResponse.setSupplierName(warehouseMap.get(good.getRealWarehouse()).getWarehouseName());
                }
            } else {
                if (supplyMap.containsKey(good.getSupplierId())) {
                    exportOrderAllResponse.setSupplierName(supplyMap.get(good.getSupplierId()).getSupplierCompanyName());
                }
            }
            AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(good.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
            if (afterSaleStatusEnum != null) {
                exportOrderAllResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
            }
            exportOrderAllResponses.add(exportOrderAllResponse);
        }
        exportExcelCommonResponse.setData(exportOrderAllResponses);
        exportExcelCommonResponse.setFileName("已完成" + System.currentTimeMillis() + ".xlsx");
        return exportExcelCommonResponse;
    }

    public ExportExcelCommonResponse<ExportOrderAllResponseC> getAfterSale(ExportCompletedRequest request) {
        ExportExcelCommonResponse<ExportOrderAllResponseC> exportExcelCommonResponse = new ExportExcelCommonResponse<>();
        List<ExportOrderAllResponseC> exportOrderAllResponses = new ArrayList<>();
        List<UserOrderGoodsInfo> orderGoodsInfos = userOrderMapper.getAfterSaleOrders(request.getId(), request.getStartTime(), request.getEndTime(), request.getGoodsName(), request.getType(), request.getSupplierId());
        if (orderGoodsInfos.isEmpty()) {
            return exportExcelCommonResponse;
        }
        //获取全部供应商
        List<JmSupplierResponse> jmSupplierResponses = getSupply();
        Map<Integer, JmSupplierResponse> supplyMap = jmSupplierResponses.stream().collect(Collectors.toMap(s -> s.getSupplierId().intValue(), s -> s));
        //获取全部发货仓
        List<JmWarehouseResponse> iJmWarehouseServiceAll = iJmWarehouseService.findAll().getData();
        Map<Integer, JmWarehouseResponse> warehouseMap = iJmWarehouseServiceAll.stream().collect(Collectors.toMap(s -> s.getWarehouseId().intValue(), s -> s));

        for (UserOrderGoodsInfo good : orderGoodsInfos) {
            ExportOrderAllResponseC exportOrderAllResponse = new ExportOrderAllResponseC();
            exportOrderAllResponse.setOrderNo(good.getOrderNo());
            exportOrderAllResponse.setCreateTime(good.getCreateTime());
            if (good.getPayTime() != null) {
                exportOrderAllResponse.setPayTime(good.getPayTime());
            }
            exportOrderAllResponse.setNickName(good.getReceiverName());
            exportOrderAllResponse.setPhone(good.getReceiverPhone());
            exportOrderAllResponse.setAddress(good.getReceiverAddress());
            OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(good.getOrderStatus(), OrderStatusEnum.class);
            if (orderStatusEnum != null) {
                exportOrderAllResponse.setOrderStatus(orderStatusEnum.getMessage());
            }
            BeanUtils.copyProperties(good, exportOrderAllResponse);
            LogisticsStatusEnum logisticsStatusEnum = EnumUtil.getByCode(good.getGoodsStatus(), LogisticsStatusEnum.class);
            if (logisticsStatusEnum != null) {
                exportOrderAllResponse.setGoodsStatusString(logisticsStatusEnum.getMsg());
            }
            if (good.getSelfFlag().equals(SelfFlagEnum.YES_SELF.getCode())) {
                if (warehouseMap.containsKey(good.getRealWarehouse())) {
                    exportOrderAllResponse.setSupplierName(warehouseMap.get(good.getRealWarehouse()).getWarehouseName());
                }
            } else {
                if (supplyMap.containsKey(good.getSupplierId())) {
                    exportOrderAllResponse.setSupplierName(supplyMap.get(good.getSupplierId()).getSupplierCompanyName());
                }
            }
            AfterSaleStatusEnum afterSaleStatusEnum = EnumUtil.getByCode(good.getAfterSealStatus().intValue(), AfterSaleStatusEnum.class);
            if (afterSaleStatusEnum != null) {
                exportOrderAllResponse.setAfterSealStatusString(afterSaleStatusEnum.getMsg());
            }
            exportOrderAllResponses.add(exportOrderAllResponse);
        }
        exportExcelCommonResponse.setData(exportOrderAllResponses);
        exportExcelCommonResponse.setFileName("售后" + System.currentTimeMillis() + ".xlsx");
        return exportExcelCommonResponse;
    }

    public ExportExcelCommonResponse<ExportFindOrderResponse> exportFindOrder(ExportFindOrderRequest request) {
        ExportExcelCommonResponse<ExportFindOrderResponse> exportFindOrderResponseExportExcelCommonResponse = new ExportExcelCommonResponse<>();
        List<Integer> orderId = new ArrayList<>();
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        if (request.getId() != null) {
            String[] ids = request.getId().split(",");
            for (String id : ids) {
                orderId.add(Integer.valueOf(id));
            }
            userOrderQueryWrapper.in("id", orderId);
        }

        userOrderQueryWrapper.orderBy(true, false, "create_time");
        if ((request.getPhoneType() == PhoneTypeEnum.BUYER.getCode())) {
//            userOrderQueryWrapper.eq("buyer_id",); 购买人id获取手机号
        } else if (request.getPhoneType() == PhoneTypeEnum.SELLER.getCode()) {
            userOrderQueryWrapper.eq("receiver_phone", request.getPhone());
        }
        if (request.getOrderNo() != null) {
            userOrderQueryWrapper.eq("order_no", request.getOrderNo());
        }
        if (request.getOrderStatus() != null) {
            userOrderQueryWrapper.eq("order_status", request.getOrderStatus());
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            userOrderQueryWrapper.between("create_time", request.getStartTime(), request.getEndTime());
        }
        if (request.getPayStartTime() != null && request.getPayEndTime() != null) {
            userOrderQueryWrapper.between("pay_time", request.getPayStartTime(), request.getPayEndTime());
        }
        List<UserOrder> userOrders = userOrderMapper.selectList(userOrderQueryWrapper);
        List<ExportFindOrderResponse> exportFindOrderResponses = new ArrayList<>();
        for (UserOrder record : userOrders) {
            ExportFindOrderResponse exportFindOrderResponse = new ExportFindOrderResponse();
            OrderStatusEnum orderStatusEnum = EnumUtil.getByCode(record.getOrderStatus(), OrderStatusEnum.class);
            BeanUtils.copyProperties(record, exportFindOrderResponse);
            exportFindOrderResponse.setOrderStatus(orderStatusEnum.getMessage());
            ResponseResult<JmUserReponse> jmUserReponseR = iMemberService.getMemberByUid(record.getBuyerId().intValue());
            exportFindOrderResponse.setBuyer(jmUserReponseR.getData().getName());
            exportFindOrderResponse.setBuyerPhone(jmUserReponseR.getData().getMobile());
            exportFindOrderResponse.setPayType(EnumUtil.getByCode(record.getPayType(), PayChannelEnum.class).getDescription());
            exportFindOrderResponses.add(exportFindOrderResponse);
        }
        exportFindOrderResponseExportExcelCommonResponse.setData(exportFindOrderResponses);
        exportFindOrderResponseExportExcelCommonResponse.setFileName("订单查询" + System.currentTimeMillis() + ".xlsx");
        return exportFindOrderResponseExportExcelCommonResponse;
    }

    /**
     * 部分发货导入
     */
    public List<String> excelImport(HttpServletRequest request, Long uid, String name) throws IOException {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        try {
            EasyExcel.read(request.getInputStream(), ExportOrderAllResponse.class, new SendListener(sendService, uid, name)).sheet().doRead();
        } catch (ExcelAnalysisException | ExcelCommonException e) {
            throw new BaseException(500, "文件异常，请检查确认");
        }
        return SendService.partSendError;
    }

    /**
     * 非自营发货导入
     *
     * @param request
     * @param uid
     * @param name
     * @return
     * @throws IOException
     */
    public List<String> excelImportNoSeal(HttpServletRequest request, Long uid, String name) throws IOException {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        try {
            EasyExcel.read(request.getInputStream(), ImportNoSelfResponse.class, new ExcelListener(uid, name, sendService)).sheet().doRead();
        } catch (ExcelAnalysisException | ExcelCommonException e) {
            throw new BaseException(500, "文件异常，请检查确认");
        }
        return SendService.noSelfWaitSendError;
    }

    /**
     * 获取所有供应商
     *
     * @return
     */
    public List<JmSupplierResponse> getSupply() {
        ResponseResult<List<JmSupplierResponse>> responseResult = iJmSupplierService.list();
        List jmSupplierResponses = responseResult.getData();
        List<JmSupplierResponse> result = new ArrayList<>();
        for (Object object : jmSupplierResponses) {
            JmSupplierResponse jmSupplierResponse = JSON.parseObject(JSON.toJSONString(object), JmSupplierResponse.class);
            result.add(jmSupplierResponse);
        }
        return result;
    }

}
